package cn.atguigu.stack;

public class StackDemo {

    public static void main(String[] args) {
        StackDemo stackDemo = new StackDemo(4);
        stackDemo.push(1);
        stackDemo.push(2);
        stackDemo.show();
        System.out.println(stackDemo.pop());
        System.out.println(stackDemo.pop());

        stackDemo.push(5);
        stackDemo.push(6);
        System.out.println(stackDemo.pop());
        stackDemo.show();
    }

    public int maxSize; //栈大小

    private int[] stack; //存放数据

    private int top = -1; //栈顶

    public StackDemo(int i){
        this.maxSize = i;
        this.stack = new int[i];
    }

    /**
     * 栈满
     * @return
     */
    public boolean isFull(){
        return top == maxSize-1;
    }

    /**
     * 栈是否为空
     * @return
     */
    public boolean isEmpty(){
        return top == -1;
    }

    public void push(int i){
        if(isFull()){
            System.out.println("栈已满");
            return;
        }
        ++top;
        stack[top] = i;
    }

    public int pop(){
        if(isEmpty()){

            throw new RuntimeException("栈空");

        }
        --top;
        return stack[top+1];
    }

    public void show(){
        if(isEmpty()){
            System.out.println("栈空不能遍历");
        }
        for (int i = top; 0 <= i ; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }

    }
}
